package com.lvchangqi.restAPI;

import com.lvchangqi.dao.DAO;
import com.lvchangqi.entity.InfoEntity;
import com.lvchangqi.entity.LeaveEntity;
import com.lvchangqi.entity.UserEntity;
import com.lvchangqi.util.*;
import com.taobao.api.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.activation.MimetypesFileTypeMap;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by version on 17-6-18.
 */
@RestController
@RequestMapping("/api")
public class RestAPI {

    @Autowired
    private Cet cet;

    @Autowired
    private College college;

    @Autowired
    private Uploading uploading;

    @Autowired
    private SMSUtil smsUtil;

    @Autowired
    private DocBuilder docBuilder;

    @Autowired
    private DAO dao;

    @RequestMapping(value = "/cet", method = RequestMethod.GET)
    public Map CETSearch(@RequestParam("zkzh") String zkzh,
                         @RequestParam("xm") String xm) throws IOException {

        return cet.instance(zkzh, xm);
    }

    @RequestMapping(value = "/studio/{step}", method = RequestMethod.GET)
    public Object StudioGet(@RequestParam(value = "status", required = false) String status,
                            @PathVariable("step") Integer step) throws IOException {

        return status == null ? college.studio() : college.studioDetail(status, step);
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Map login(@RequestParam("student_id") String id,
                     @RequestParam("password") String password) throws NoSuchAlgorithmException {
        Map<String, Object> result = new HashMap<>();
        password = new BASE64Encoder().encode(
                MessageDigest.getInstance("MD5").digest(password.getBytes()));
        UserEntity user = dao.getUser(id);
        if (user == null) {
            result.put("code", 404);
            result.put("result", "此app只提供暂只提供给教技学院使用,敬请期待后续开放");
        } else {
            if (!user.getPassword().equals(password)) {
                result.put("code", 403);
                result.put("result", "密码错误");
            } else {
                result.put("code", 200);
                result.put("result", user);
            }
        }
        return result;
    }

    @RequestMapping(value = "/leave", method = RequestMethod.POST)
    public Boolean leaveApplyWithCase(LeaveEntity leave, MultipartFile illness) throws IOException, InterruptedException, ApiException {
        if (illness != null) {
            String original = illness.getOriginalFilename();
            String fileName = "病例/" + leave.getName() + "/"
                    + new SimpleDateFormat("yyyy-MM-dd").format(new Date())
                    + original.substring(original.lastIndexOf("."));
            String contentType = URLConnection.getFileNameMap().getContentTypeFor(fileName);

            String url = uploading
                    .upload(illness.getInputStream(), contentType, fileName)
                    .toString();
            leave.setUrl(url.substring(0, url.lastIndexOf("?")));
        }

        dao.saveCase(leave);

        InfoEntity infoEntity = dao.getTeacherInfo(leave.getClazz());
        smsUtil.sendSMStoTeacher(infoEntity.getPhone(), infoEntity.getName(), leave.getName(), leave.getPhone_m());

        return true;
    }

    @RequestMapping(value = "/review/teacher", method = RequestMethod.POST)
    public Boolean teacherReview(@RequestBody Map<String, String> map) throws ApiException {
        if (map.containsKey("t_version")){
            if(Integer.parseInt(map.get("days")) < 3){
                smsUtil.sendSMStoLeader("18672023053", "付静老师", map.get("clazz"), map.get("name"));
            }
            if(Integer.parseInt(map.get("days")) >= 3){
//                smsUtil.sendSMStoLeader("", "林松书记", map.get("clazz"), map.get("name"));
                System.out.println("发送短信给林书记");
            }
        }

        dao.updateLeave(map);
        return true;
    }

    @RequestMapping(value = "/review/{role}", method = RequestMethod.GET)
    public List reviewLeave(@RequestParam("info_id") Integer infoId,
                            @PathVariable("role") Integer role){

        return dao.getLeaves(infoId, role);
    }

    @RequestMapping(value = "/doc", method = RequestMethod.POST)
    public Boolean renderDoc(@RequestBody Map<String, String> map) throws Exception {
        LeaveEntity leaveEntity = dao.getLeave(Integer.parseInt(map.get("id")));
        List<InputStream> list = new LinkedList<>();

        String leaderSign = "付静";
        if(Integer.parseInt(map.get("days")) >= 3){
            leaderSign = "林松";
        }

        String teacherSign = dao.getTeacherInfo(map.get("clazz")).getName();

        list.add(new URL("http://bucket-vacate.nos-eastchina1.126.net/sign/"+teacherSign+".png") .openStream());
        list.add(new URL("http://bucket-vacate.nos-eastchina1.126.net/sign/"+leaderSign+".png") .openStream());
        list.add(new URL("http://bucket-vacate.nos-eastchina1.126.net/sign/"+teacherSign+".png") .openStream());
        list.add(new URL("http://bucket-vacate.nos-eastchina1.126.net/sign/"+leaderSign+".png") .openStream());

        System.out.println(list.size());
        System.out.println(list.get(0));
        System.out.println(list.get(1));
        new MailBuilder("测试", "测试", map.get("email"))
                .build(docBuilder.build(leaveEntity, list));

        return true;
    }
}
